package ntd.util.modular.data.util.handle;

import cn.hutool.extra.spring.SpringUtil;
import ntd.block.server.bo.ComServerMsgBo;
import ntd.block.server.listen.ComAbsServerListen;
import ntd.util.frame.server.util.UtilServer;
import ntd.util.modular.data.entity.DataAcquisitionRecords;
import ntd.util.modular.data.entity.DataAcquisitionRule;
import ntd.util.config.common.enums.data.EnumDataAcquisitionType;
import ntd.util.config.common.enums.data.EnumProtocolType;
import ntd.util.modular.data.service.DataAcquisitionRecordsService;
import ntd.util.modular.data.util.handle.bo.ComRuleConfigBo;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class ComDataGetRuleTcp implements ComDataGetRule {

    private static DataAcquisitionRecordsService dataAcquisitionRecordsService;

    @PostConstruct
    public void init() {
        dataAcquisitionRecordsService = SpringUtil.getBean(DataAcquisitionRecordsService.class);
    }

    @Override
    public Object handle(DataAcquisitionRule dataAcquisitionRule) {
        if (!dataAcquisitionRule.getEnumProtocolType().equals(EnumProtocolType.TCP)) {
            return "非TCP协议，不能执行该模块！";
        }

        if (dataAcquisitionRule.getEnumDataAcquisitionType().equals(EnumDataAcquisitionType.RULE_ACTIVE)) {

        }
        if (dataAcquisitionRule.getEnumDataAcquisitionType().equals(EnumDataAcquisitionType.RULE_PASSIVE)) {
            ComRuleConfigBo comRuleConfigBo = ComRuleConfigBo.transform(dataAcquisitionRule.getExtendJson());
            UtilServer.addListen(comRuleConfigBo.getServerAppId(), new ComAbsServerListen(){
                @Override
                public ComServerMsgBo onMsg(ComServerMsgBo comServerMsgBo) {
                    handleMsg(comServerMsgBo.getMsg(), dataAcquisitionRule);
                    return null;
                }
            });
        }
        return "规则执行成功";
    }

    public void handleMsg(String msg, DataAcquisitionRule dataAcquisitionRule) {
        DataAcquisitionRecords dataAcquisitionRecords = new DataAcquisitionRecords();
        dataAcquisitionRecords.setDataAcquisitionRuleId(dataAcquisitionRule.getId());
        dataAcquisitionRecords.setTenantId(dataAcquisitionRule.getTenantId());
        dataAcquisitionRecords.setContent(msg);
        dataAcquisitionRecordsService.saveOrUpdate(dataAcquisitionRecords);
    }

    @Override
    public void close() {
    }

}
